﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model_SSResourceManager;
using Presenter_SSResourceManager;

namespace WebView_SSResourceManager.UserPages
{
    public partial class Booking : System.Web.UI.Page, IViewBooking
    {
        private PresenterBooking _bookingPresenter;

        protected void Page_Load(object sender, EventArgs e)
        {   
            _bookingPresenter = new PresenterBooking(this);
            if(!IsPostBack)
            _bookingPresenter.FillQueueFildsbyPattern(GetUserID(),GetResourceId());
        }

        public Guid GetResourceId()
        {
            var query = HttpContext.Current.Request.Url.Query.Where(symbol => symbol != '?');

            try
            {
                return Guid.Parse(new string(query.ToArray()));
            }
            catch (Exception)
            {
                Response.Redirect("~/");
            }

            return new Guid();
        }

        private Guid GetUserID()
        {
            return Guid.Parse(Server.HtmlEncode(Request.Cookies["UID"].Value));
        }

        protected void btn_ChechQueue_OnClick(object sender, EventArgs e)
        {
            var currentResource = (Resource)Session["Resource"];
            try
            {
                if (currentResource.StartTime > TimeSpan.Parse(txtB_StartTime.Text) ||
                    currentResource.EndTime < TimeSpan.Parse(txtB_EndTime.Text) ||
                    currentResource.TimeOfUsing < TimeSpan.Parse(txtB_EndTime.Text) - TimeSpan.Parse(txtB_StartTime.Text))
                {
                    lbl_BookingResult.Text = "Time asked the wrong, check the policy of the resource";
                    lbl_BookingResult.ForeColor = System.Drawing.Color.Red;
                }

                else
                {
                    var queue = (Queue)Session["Queue"];
                    var newQueue = GatherQueuesFields();
                    queue.StartTime = newQueue.StartTime;
                    queue.FinishTime = newQueue.FinishTime;
                    queue.MessageTime = _bookingPresenter.GetUserMessageSetting(queue.IdUser,queue.StartTime);
                    var result = new StringBuilder();
                    var resultString = _bookingPresenter.CheckAvailable(queue);

                    foreach (string[] sentense in resultString)
                        foreach (string word in sentense)
                            result.AppendFormat("{0} ", word);
                    

                    lbl_BookingResult.Text = result.ToString();
                    SetResultColor();
                }
            }
            catch (Exception)
            {
                lbl_BookingResult.Text = "Incorrect time format";
                lbl_BookingResult.ForeColor = System.Drawing.Color.Red;
            }
        }

        protected void btn_Book_OnClick(object sender, EventArgs e)
        {
            btn_ChechQueue_OnClick(sender,e);
            if (lbl_BookingResult.Text[0] == 'A')
            {
                _bookingPresenter.AddQueue();
                lbl_BookingResult.Text = "Booked";
                lbl_BookingResult.ForeColor = System.Drawing.Color.Green;
                _bookingPresenter.AddQueue();
            }
            else
            {
                lbl_BookingResult.Text = "Checking Failed";
                lbl_BookingResult.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void SetResultColor()
        {
            char letter = lbl_BookingResult.Text[0];
            if (letter == 'A')
                lbl_BookingResult.ForeColor = System.Drawing.Color.Green;
            else if(letter == 'W')
                lbl_BookingResult.ForeColor = System.Drawing.Color.DarkOrange;
            else
                lbl_BookingResult.ForeColor = System.Drawing.Color.Red;
            
        }

        public Queue GatherQueuesFields()
        {
            var queue = (Queue) Session["Queue"];
            queue.StartTime = DateTime.Today + TimeSpan.Parse(txtB_StartTime.Text);
            queue.FinishTime = DateTime.Today + TimeSpan.Parse(txtB_EndTime.Text);
            return queue;
        }


        public void FillFieldsQueue(Queue queue)
        {
            Session["Queue"] = queue;
            txtB_StartTime.Text = DateTime.Now.ToShortTimeString();
            txtB_EndTime.Text = (DateTime.Now + ((Resource)Session["Resource"]).TimeOfUsing).ToShortTimeString();
        }

        public void FillResourceFilds(Resource resource)
        {
            Session["Resource"] = resource;
            lbl_AutoTime.Text = resource.OnlyAutoTime.ToString();
            lbl_Available.Text = (!resource.Locked).ToString();
            lbl_EndTime.Text = resource.EndTime.ToString();
            lbl_ResourceName.Text = resource.Name;
            lbl_StartTime.Text = resource.StartTime.ToString();
            lbl_UseTime.Text = resource.TimeOfUsing.ToString();
            lbl_UserCount.Text = resource.UserCount.ToString();
        }
    }
}